<?php

namespace longhu\base;

use app\Request;
use longhu\exceptions\FailedException;
use longhu\exceptions\ValidateFailedException;
use longhu\Utils;
use Spatie\Macroable\Macroable;

/**
 *  @method isAdminLogin() 后台登陆状态
 * @method adminId() 后台管理员id
 * @method adminType() 后台管理员id
 * @method adminShopId() 后台管理员id
 * @method adminInfo() 后台管理信息
 */
class AdminBaseRequest extends Request
{
    use Macroable;
    /**
     * @var bool
     */
    protected $needCreatorId = true;
    /**
     *  批量验证
     *
     * @var bool
     */
    protected $batch = false;


    /**
     * Request constructor.
     * @throws \Exception
     */
    public function __construct()
    {
        parent::__construct();

        $this->validate();
    }


    /**
     * 获取请求的数据
     * @param array $params
     * @param bool $suffix
     * @param bool $filter
     * @return array
     */
    public function more(array $params, bool $suffix = false, bool $filter = true): array
    {
        $p = [];
        $i = 0;
        foreach ($params as $param) {
            if (!is_array($param)) {
                $p[$suffix == true ? $i++ : $param] = $this->filterWord(is_string($this->param($param)) ? trim($this->param($param)) : $this->param($param), $filter && !in_array($param, $this->except));
            } else {
                if (!isset($param[1])) $param[1] = null;
                if (!isset($param[2])) $param[2] = '';
                if (is_array($param[0])) {
                    $name = is_array($param[1]) ? $param[0][0] . '/a' : $param[0][0] . '/' . $param[0][1];
                    $keyName = $param[0][0];
                } else {
                    $name = is_array($param[1]) ? $param[0] . '/a' : $param[0];
                    $keyName = $param[0];
                }
                $p[$suffix == true ? $i++ : ($param[3] ?? $keyName)] = $this->filterWord(is_string($this->param($name, $param[1], $param[2])) ? trim($this->param($name, $param[1], $param[2])) : $this->param($name, $param[1], $param[2]), $filter && !in_array($keyName, $this->except));
            }
        }
        return $p;
    }
    /**
     * 过滤接受的参数
     * @param $str
     * @param bool $filter
     * @return array|mixed|string|string[]
     */
    public function filterWord($str, bool $filter = true)
    {
        if (!$str || !$filter) return $str;
        // 把数据过滤
        $farr = [
            "/<(\\/?)(script|i?frame|style|html|body|title|link|meta|object|\\?|\\%)([^>]*?)>/isU",
            "/(<[^>]*)on[a-zA-Z]+\s*=([^>]*>)/isU",
            "/select|join|where|drop|like|modify|rename|insert|update|table|database|alter|truncate|\'|\/\*|\.\.\/|\.\/|union|into|load_file|outfile/is"
        ];
        if (is_array($str)) {
            foreach ($str as &$v) {
                if (is_array($v)) {
                    foreach ($v as &$vv) {
                        if (!is_array($vv)) $vv = preg_replace($farr, '', $vv);
                    }
                } else {
                    $v = preg_replace($farr, '', $v);
                }
            }
        } else {
            $str = preg_replace($farr, '', $str);
        }
        return $str;
    }

    /**
     * 初始化验证
     *
     * @time 2019年11月27日
     * @throws \Exception
     * @return mixed
     */
    protected function validate()
    {

        if (method_exists($this, 'rules')) {
            try {
                $validate = app('validate');
                // 批量验证
                if ($this->batch) {
                    $validate->batch($this->batch);
                }
                // 验证
                $message = [];
                if (method_exists($this, 'message')) {
                    $message = $this->message();
                }
                if (!$validate->message(empty($message) ? [] : $message)->check(request()->param(), $this->rules())) {
                    throw new FailedException($validate->getError());
                }
            } catch (\Exception $e) {
                throw new ValidateFailedException($e->getMessage());
            }
        }

//        // 设置默认参数
//        if ($this->needCreatorId) {
//            $this->param['creator_id'] = $this->adminId();
//        }
        return true;
    }

    /**
     * rewrite post
     *
     * @time 2020年10月15日
     * @param string $name
     * @param null $default
     * @param string $filter
     * @return array|mixed|null
     */
    public function post($name = '', $default = null, $filter = '')
    {
        if ($this->needCreatorId) {
            $this->post['creator_id'] =$this->adminId();
        }

        return parent::post($name, $default, $filter); // TODO: Change the autogenerated stub
    }

    /**
     * 过滤空字段
     *
     * @time 2021年01月16日
     * @return $this
     */
    public function filterEmptyField(): AdminBaseRequest
    {
        if ($this->isGet()) {
            $this->get = Utils::filterEmptyValue($this->get);
        } elseif ($this->isPost()) {
            $this->post =  Utils::filterEmptyValue($this->post);
        } else {
            $this->put =  Utils::filterEmptyValue($this->put);
        }

        return $this;
    }

    /**
     * 获取用户访问端
     * @return array|string|null
     */
    public function getFromType()
    {
        return $this->header('Form-type', '');
    }

    /**
     * 当前访问端
     * @param string $terminal
     * @return bool
     */
    public function isTerminal(string $terminal)
    {
        return strtolower($this->getFromType()) === $terminal;
    }
    /**
     * 是否是app端
     * @return bool
     */
    public function isApp()
    {
        return $this->isTerminal('app');
    }

    /**
     * 是否是app端
     * @return bool
     */
    public function isPc()
    {
        return $this->isTerminal('pc');
    }
}